package
{
	import com.greensock.TweenLite;
	import com.greensock.TweenMax;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import net.hires.debug.Stats;
	import petrus.components.events.ComponentEvent;
	import petrus.components.scroll.AbstractScrollBar;
	import petrus.mood.grid.Board;
	import petrus.mood.grid.BoardEvent;
	import petrus.utils.BandWidthUtil;
	
	/**
	 * ...
	 * @author Benoit Petrus
	 */
	public class Main extends Sprite
	{
		public static var INSTANCE:Main;
		static private const SCROLL_W:Number = 12;
		private var _xmlLoader:URLLoader;
		private var _board:Board;
		private var _scroll:AbstractScrollBar;
		private var countError:int = 0;
		private var START_COUNT:int = 0;
		private var TUMBLR_ID:String;
		private var s:Stats;
		
		public function Main():void
		{
			INSTANCE = this
			if (stage)
				init();
			else
				addEventListener(Event.ADDED_TO_STAGE, init);
				
		
		}
		
		private function init(e:Event = null):void
		{
			/*
			   var b : BandWidthUtil = new BandWidthUtil("http://upload.wikimedia.org/wikipedia/commons/7/70/Deathvalleysky_nps_big.jpg")
			   b.start()
			 */
			alpha = 0
			stage.scaleMode = StageScaleMode.NO_SCALE
			stage.align = StageAlign.TOP_LEFT
			stage.addEventListener(Event.RESIZE, resizeHandler)
			removeEventListener(Event.ADDED_TO_STAGE, init);
			loadXML();
		}
		
		private function resizeHandler(e:Event):void
		{
			if (_board)
			{
				_board.x = (stage.stageWidth - _board.width) / 2;
				_scroll.x = Math.floor(stage.stageWidth - _scroll.width);
				_scroll.y = 0;
				_scroll.resize(SCROLL_W, stage.stageHeight - 0);
			}
		}
		
		private function loadXML():void
		{
			TUMBLR_ID = "mankindproject";
			TUMBLR_ID = "benoit3000";
			TUMBLR_ID = "thisturnsmeon";
			TUMBLR_ID = "film-grain";
			
			if (this.loaderInfo.parameters.tumblr)
				TUMBLR_ID = this.loaderInfo.parameters.tumblr;
			
			var url:String = "http://" + TUMBLR_ID + ".tumblr.com/api/read?start=" + START_COUNT + "&num=50";
			
			_xmlLoader = new URLLoader();
			_xmlLoader.addEventListener(Event.COMPLETE, onComplete)
			_xmlLoader.addEventListener(IOErrorEvent.DISK_ERROR, errorHandler)
			_xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler)
			_xmlLoader.load(new URLRequest(url));
			trace("[Main.loadXML] parameters.tumblr " + this.loaderInfo.parameters.tumblr);
			trace("[Main.loadXML]url  " + url);
		}
		
		private function reload():void
		{
			trace("[Main.reload] ");
			START_COUNT += 50;
			var url:String = "http://" + TUMBLR_ID + ".tumblr.com/api/read?start=" + START_COUNT + "&num=" + (START_COUNT + 50);
			_xmlLoader.load(new URLRequest(url));
			_xmlLoader.addEventListener(Event.COMPLETE, onComplete)
		}
		
		private function errorHandler(e:Event):void
		{
			trace("[Main.errorHandler] " + e.type);
			countError++
			if (countError == 2)
				return _xmlLoader.load(new URLRequest("xml/offline.xml"));
		}
		
		private function onComplete(e:Event):void
		{
			if (START_COUNT == 0)
			{
				TweenLite.to(this, .5, {alpha: 1});
				addScroll();
				addBoard();
				stage.dispatchEvent(new Event(Event.RESIZE));
			}
			else
			{
				_board.build(XML(_xmlLoader.data))
			}
			
			removeLoader()
		}
		
		private function removeLoader():void
		{
			_xmlLoader.removeEventListener(Event.COMPLETE, onComplete)
			_xmlLoader.removeEventListener(IOErrorEvent.DISK_ERROR, errorHandler)
			_xmlLoader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler)
			_xmlLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, errorHandler)
			//_xmlLoader = null
		}
		
		private function addBoard():void
		{
			_board = new Board()
			//_board.visible = false
			addChild(_board);
			swapChildren(_board, _scroll)
			//_board.addEventListener(BoardEvent.START_LOADING, boardHandler)
			_board.addEventListener(BoardEvent.STOP_LOADING, boardHandler)
			_board.addEventListener(BoardEvent.LOADED, boardHandler)
			_board.build(XML(_xmlLoader.data))
			
			s= new Stats()
			addChild(s)
		}
		
		private function boardHandler(e:BoardEvent):void
		{
			switch (e.type)
			{
				case BoardEvent.LOADED: 
					//trace("[Main.boardHandler] loaded , loaded " + e.type);				
					reload()
				
				//case BoardEvent.START_LOADING: 	
				//break;
				case BoardEvent.STOP_LOADING: 
					_scroll.forcePercentPos(_board.percent, false);
					stage.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel)
					break;
			}
		}
		
		private function addScroll():void
		{
			_scroll = new AbstractScrollBar(false);
			_scroll.easing = 3.5;
			_scroll.mouseWheelDelta = 18;
			addChild(_scroll);
			_scroll.resize(12, stage.stageHeight - 60);
			_scroll.enable();
			_scroll.addEventListener(ComponentEvent.CHANGE, scrollHandler);
		}
		
		private function onMouseWheel(e:MouseEvent):void
		{
			var delta:Number;
			if (e.delta > 0)
				delta = 3;
			else
				delta = -3;
			
			/*
			   _scroll.renderWheel(-delta);
			 */
			
			_board.onMouseWheel(delta)
			_scroll.forcePercentPos(_board.percent, false);
		
			//trace("[Main.onMouseWheel] "+_board.percent);
		}
		
		private function scrollHandler(e:ComponentEvent):void
		{
			if (_board.updatePos(_scroll.percent))
			{
				_scroll._render()
			}
		}
	}
}